package com.whut.f2f.chat.message;

import com.whut.f2f.chat.connector.Connector;
import com.whut.f2f.common.util.Json;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * 消息处理
 *
 * Created by null on 2017/1/25.
 */
public class MessageProcessor {

    private static final Logger log = LoggerFactory.getLogger(MessageProcessor.class);

    public void process(String msg, Channel channel, Connector connector) {
        HashMap data = Json.parse(HashMap.class, msg);
        if (data == null || data.isEmpty()) {
            return;
        }
        String scope = (String) data.get("scope");
        switch (scope) {
            case "ping":
                processPingScope(data, channel, connector);
                break;
            case "send":
                processSendScope(data, channel, connector);
                break;
            default:
                connector.send((String) data.get("from"), "{\"code\": 412, \"msg\": \"格式不正确!\"}");
                log.warn("unknown message scope!");
        }
    }

    private void processPingScope(HashMap data, Channel channel, Connector connector) {
        String from = (String) data.get("from");
        log.debug("[{}] ping...", from);
        connector.add(from, channel);
        connector.send(from, Json.parse(data));
        // 从服务端拉取离线消息
    }

    private void processSendScope(HashMap data, Channel channel, Connector connector) {
        if (!MessageValidation.sendMessageValid(data)) {
            String from = (String) data.get("from");
            connector.send(from, "{\"code\": 412, \"msg\": \"格式不正确!\"}");
            log.warn("invalid message type from [{}]!", from);
            return;
        }
        String to = (String) data.get("to");
        // 发送的用户是否在线，不在线设置离线消息

        // 在线则发送
        connector.send(to, Json.parse(data));
    }

}
